package com.sky.controller.user;

import com.alibaba.fastjson.JSON;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.result.Result;
import com.sky.service.SetMealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController("userSetMealController")
@RequestMapping("/user/setmeal")
@Slf4j
@Api(tags = "浏览菜品相关接口:三")
public class SetMealController {
    @Autowired
    SetMealService setmealService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @GetMapping("/dish/{id}")
    @ApiOperation(value = "根据套餐id查询相关菜品")
    public Result<List<SetmealDish>> getDish(@PathVariable Long id){
        return Result.success(setmealService.getDishBySetmealId(id));
    }
    @GetMapping("/list")
    @ApiOperation(value = "根据分类id查询套餐")
    public Result<List<Setmeal>> list(Long categoryId){
//        List<Setmeal> list = setmealService.list(categoryId);
//        stringRedisTemplate.opsForValue().set("setmealCache::"+categoryId, list.toString());
//        和缓存菜品一样的逻辑,如果redis里有数据,就从直接返回redis的数据
//        如果没有数据,就加入缓存
        String key = "setmealCache::"+categoryId;
        List<String> stringList = stringRedisTemplate.opsForList().range(key, 0, -1);
        if (stringList != null && !stringList.isEmpty()) {
            System.out.println("直接从缓存里查数据");
            List<Setmeal> list = new ArrayList<>();
            for(String string:stringList){
                list.add(JSON.parseObject(string, Setmeal.class));
            }
            return Result.success(list);
        }
        else {
            System.out.println("缓存里没有数据");
            List<Setmeal> list = setmealService.list(categoryId);
            for(Setmeal setmeal:list){
                stringRedisTemplate.opsForList().rightPush(key, JSON.toJSONString(setmeal));
            }
            return Result.success(list);
        }
    }
}
